package cn.e4j.modular.api.controller;

import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.api.service.GwaService;
import cn.e4j.modular.api.service.Gwat310Service;
import cn.e4j.modular.api.service.GwbService;
import cn.e4j.modular.api.util.CommonUtils;
import cn.e4j.modular.api.util.ControllerSupport;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.service.impl.SystemServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单确认 控制类
 * Created by shixc on 2018/4/28.
 */
@RestController
@RequestMapping("api/wx/gwat310")
public class Gwat310Controller extends ControllerSupport {
    private static Logger logger = LoggerFactory.getLogger(Gwat310Controller.class);

    @Autowired
    Gwat310Service gwat310Service;

    @Autowired
    private GwaService gwaService;

    @Autowired
    SystemServiceImpl systemService;

    @Autowired
    GwbService gwbService;

    /**
     * 获取订单信息
     *
     * @return
     */
    @PostMapping(value = "getGwcsDatas")
    public ResponseData getGwcsDatas(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser user = wapper.getSysUser();
        List<Dto> list = new ArrayList<Dto>();
        try {
            String gwcsacti = inDto.getString("GWCSACTI");
            if ("1".equals(gwcsacti)) {
                inDto.put("GWCSACTI", "N");
            } else if ("2".equals(gwcsacti)) {
                inDto.put("GWCSACTI", "Y");
            }
            //客户权限
            Dto gwb001 = gwbService.getGwb001(user, inDto);
            inDto.put("CUSTOMERS", gwb001.get("CUSTOMERS"));

            //上下级权限
            Dto sys003 = systemService.getSys003(user);
            inDto.put("ORGS", sys003.get("ORGS"));

            list = gwat310Service.getGwcsData(wapper.getPage(), inDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(list);
    }

    /**
     * 确认订单 -- 单笔
     *
     * @param wapper
     * @return
     */
    @RequestMapping("confirm")
    public ResponseData confirm(@DtoParam DtoWapper wapper) {
        Dto inDto = JSONObject.parseObject(wapper.getDto().getString("obj"), Dto.class);
        String ent = wapper.getDto().getString("ENT");
        inDto.put("ENT", ent);
        inDto.put("GWCSENT", ent);
        SysUser currentUser = wapper.getSysUser();
        int errcode = 200;
        String errmsg = "ok";
        try {
            inDto.put("type", "single");
            String result = gwat310Service.validate(inDto);
            if (ToolUtil.isEmpty(result)) {
                gwat310Service.confirm(currentUser,inDto);
            } else {
                errmsg = result;
                errcode = 500;
            }
        } catch (Exception e) {
            e.printStackTrace();
            errcode = 500;
            errmsg = "服务器出小差了";
        }

        if (errcode==200){
            List<String> mobileList = new ArrayList<>();
            try {
                List<Dto> listDto = new ArrayList<Dto>();
                listDto = CommonUtils.toJavaList(inDto.getString("list"),Dto.class);
                for (Dto dto : listDto) {
                    if (ToolUtil.isNotEmpty(dto.getString("GWCS007"))) {
                        mobileList.add(dto.getString("GWCS007"));
                    }

                    if (ToolUtil.isNotEmpty(dto.getString("GWCS013"))) {
                        mobileList.add(dto.getString("GWCS013"));
                    }
                }

                if (mobileList.size() > 0) {
                    Dto gwaaDto = Dtos.newDto();
                    gwaaDto.put("GWAAENT", inDto.getString("ENT"));
                    gwaaDto.put("GWAAACTI", "Y");
                    gwaaDto.put("GWAA004S", listDto);
//                    此处发消息的功能先去掉
                    /*List<Dto> sysUser1 = gwaService.getGwaUserByMobiles(gwaaDto);
                    WeixinHandler.sendMsg(sysUser1,
                            String.format("订单[%s]：审核结果[确认订单], 审核时间[%s], 审核人[%s]",
                                    inDto.getString("GWCSDOCNO"),
                                    DateUtils.getDate(DateUtils.PATTERN_yyyy_MM_dd_HH_mm_ss),
                                    currentUser.getNAME())
                    );*/
                }

            } catch (Exception e) {
                e.printStackTrace();
                return ERROR;
            }
        }
        return new ResponseData(errcode,errmsg);
    }

    /**
     * 取消确认订单 -- 单笔
     *
     * @return
     */
    @PostMapping("reconfirm")
    public ResponseData reconfirm(@DtoParam DtoWapper wapper) {
        Dto inDto = JSONObject.parseObject(wapper.getDto().getString("obj"), Dto.class);
        String ent = wapper.getDto().getString("ENT");
        inDto.put("ENT", ent);
        inDto.put("GWCSENT", ent);
        SysUser currentUser = wapper.getSysUser();
        JSONObject inJson = new JSONObject();
        int errcode = 200;
        String errmsg = "ok";
        try {
            inJson = JSONObject.parseObject(JSON.toJSONString(inDto.getList("list").get(0)));
            Dto _inDto = Dtos.newDto();
            _inDto.put("GWCSDOCNO", inJson.getString("GWCSDOCNO"));
            _inDto.put("GWCSENT", currentUser.getDBC());
            _inDto.put("GWCSACTI", inJson.getString("GWCSACTI"));
            String result = gwat310Service.check(_inDto);
            if (ToolUtil.isEmpty(result)) {
                gwat310Service.reconfirmSingle(inDto);
            } else {
                errcode = 500;
                errmsg = result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            errcode = 500;
            errmsg = "服务器出小差了";
        }

        if (errcode==200){

            List<String> mobileList = new ArrayList<>();
            try {
                JSONArray list = (JSONArray)inDto.get("list");
                for (Object dto : list) {
                    JSONObject item = (JSONObject) dto;

                    if (ToolUtil.isNotEmpty(item.getString("GWCS007"))) {
                        mobileList.add(item.getString("GWCS007"));
                    }

                    if (ToolUtil.isNotEmpty(item.getString("GWCS013"))) {
                        mobileList.add(item.getString("GWCS013"));
                    }
                }

                if (mobileList.size() > 0) {
                    Dto gwaaDto = Dtos.newDto();
                    gwaaDto.put("GWAAENT", inDto.getString("ENT"));
                    gwaaDto.put("GWAAACTI", "Y");
                    gwaaDto.put("GWAA004S", mobileList);
//                    此处发消息的功能先去掉
                    /*List<Dto> sysUser1 = gwaService.getGwaUserByMobiles(gwaaDto);
                    WeixinHandler.sendMsg(sysUser1,
                            String.format("订单[%s]：审核结果[取消确认], 审核时间[%s], 审核人[%s]",
                                    inJson.getString("GWCSDOCNO"),
                                    DateUtils.getDate(DateUtils.PATTERN_yyyy_MM_dd_HH_mm_ss),
                                    currentUser.getNAME())
                    );*/
                }

            } catch (Exception e) {
                e.printStackTrace();
                return ERROR;
            }
        }
        return new ResponseData(errcode,errmsg);
    }

    /**
     * 取消确认订单 -- 批量
     *
     * @param wapper
     * @return
     */
    @RequestMapping("reconfirmlist")
    public ResponseData reconfirmlist(@DtoParam DtoWapper wapper) {
        SysUser currentUser = wapper.getSysUser();
        Dto inDto = wapper.getDto();
        int errcode = 200;
        String errmsg = "ok";
        List<Dto> docnoList = new ArrayList<Dto>();
        String ent = inDto.getString("ENT");
        List<Dto> items = CommonUtils.toJavaList(wapper.getDto().getString("items"),Dto.class);
        try {

            for (Dto item : items) {
                item.put("ENT",ent);
                String result = gwat310Service.check(item);
                if (ToolUtil.isEmpty(result)) {
                    Dto docno = gwat310Service.reconfirm(item);
                    docnoList.add(docno);
                } else {
                    if ("ok".equals(errmsg)) {
                        errmsg = result;
                    } else {
                        errmsg = errmsg + result;
                    }
                    errcode = 500;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            errcode = 500;
            errmsg="服务器出小差了";
        }

        if (errcode==200){

            Dto gwaaDto = Dtos.newDto();
            gwaaDto.put("GWAAENT", inDto.getString("ENT"));
            gwaaDto.put("GWAAACTI", "Y");

            try {
                for (Dto item : items) {
                    List<String> mobileList = new ArrayList<>();
                    List<Map> listDto = (List<Map>) item.getList("list");
                    for (Map map : listDto) {
                        if (ToolUtil.isNotEmpty(map.get("GWCS007"))) {
                            mobileList.add(map.get("GWCS007").toString());
                        }

                        if (ToolUtil.isNotEmpty(map.get("GWCS013"))) {
                            mobileList.add(map.get("GWCS013").toString());
                        }
                    }

                    if (mobileList.size() > 0) {
                        gwaaDto.put("GWAA004S", mobileList);
                        /*List<Dto> sysUser1 = gwaService.getGwaUserByMobiles(gwaaDto);
                        WeixinHandler.sendMsg(sysUser1,
                                String.format("订单[%s]：审核结果[取消确认], 审核时间[%s], 审核人[%s]",
                                        item.getString("GWCSDOCNO"),
                                        DateUtils.getDate(DateUtils.PATTERN_yyyy_MM_dd_HH_mm_ss),
                                        currentUser.getNAME())
                        );*/
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new ResponseData(errcode,errmsg);
    }

    /**
     * 作废订单 -- 单笔
     *
     * @return
     */
    @PostMapping("delete")
    public ResponseData delete(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        Dto outDto = Dtos.newDto();
        int errcode = 200;
        String errmsg = "ok";
        JSONObject inJson = new JSONObject();
        SysUser currentUser = wapper.getSysUser();
        try {
            inJson = JSONObject.parseObject(inDto.getString("obj"));
            Dto _inDto = Dtos.newDto();
            _inDto.put("GWCSDOCNO", inJson.getString("GWCSDOCNO"));
            _inDto.put("GWCSENT", inDto.getString("ENT"));
            _inDto.put("GWCSACTI", inJson.getString("GWCSACTI"));

            String result = gwat310Service.check(_inDto);
            if (ToolUtil.isEmpty(result)) {
                gwat310Service.delete(_inDto);
            } else {
                errmsg = result;
                errcode = 500;
            }
        } catch (Exception e) {
            e.printStackTrace();
            errcode = 500;
            errmsg = "服务器出小差了";
        }

        if (errcode == 200) {
            List<String> mobileList = new ArrayList<>();
            try {
                JSONArray list = inJson.getJSONArray("list");
                for (Object dto : list) {
                    JSONObject item = (JSONObject) dto;

                    if (ToolUtil.isNotEmpty(item.getString("GWCS007"))) {
                        mobileList.add(item.getString("GWCS007"));
                    }

                    if (ToolUtil.isNotEmpty(item.getString("GWCS013"))) {
                        mobileList.add(item.getString("GWCS013"));
                    }
                }

                if (mobileList.size() > 0) {
                    Dto gwaaDto = Dtos.newDto();
                    gwaaDto.put("GWAAENT", "80");
                    gwaaDto.put("GWAAACTI", "Y");
                    gwaaDto.put("GWAA004S", mobileList);
                    /*List<Dto> sysUser1 = gwaService.getGwaUserByMobiles(gwaaDto);
                    WeixinHandler.sendMsg(sysUser1,
                            String.format("订单[%s]：审核结果[作废], 审核时间[%s], 审核人[%s]",
                                    inJson.getString("GWCSDOCNO"),
                                    DateUtils.getDate(DateUtils.PATTERN_yyyy_MM_dd_HH_mm_ss),
                                    currentUser.getNAME())
                    );*/
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new ResponseData(errcode,errmsg);
    }

    /**
     * 作废订单 -- 批量
     *
     * @return
     */
    @RequestMapping("deletelist")
    public ResponseData deletelist(@DtoParam DtoWapper wapper) {

        Dto inDto = wapper.getDto();
        List<Dto> items = CommonUtils.toJavaList(inDto.getString("items"),Dto.class);
        SysUser currentUser = wapper.getSysUser();
        int errcode = 200;
        String errmsg = "ok";
        ResponseData res = new ResponseData();
        try {

            res = gwat310Service.deleteBatch(inDto,items);
            errcode = res.getCode();
            errmsg = res.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            errcode = 500;
            errmsg = "服务器出小差了";
        }

        if (errcode == 200) {
            Dto gwaaDto = Dtos.newDto();
            gwaaDto.put("GWAAENT", currentUser.getDBC());
            gwaaDto.put("GWAAACTI", "Y");

            try {
                for (Dto item : items) {
                    List<String> mobileList = new ArrayList<>();
                    List<Map> listDto = (List<Map>) item.getList("list");
                    for (Map map : listDto) {
                        if (ToolUtil.isNotEmpty(map.get("GWCS007"))) {
                            mobileList.add(map.get("GWCS007").toString());
                        }

                        if (ToolUtil.isNotEmpty(map.get("GWCS013"))) {
                            mobileList.add(map.get("GWCS013").toString());
                        }
                    }

                    if (mobileList.size() > 0) {
                        gwaaDto.put("GWAA004S", mobileList);
                        /*List<Dto> sysUser1 = gwaService.getGwaUserByMobiles(gwaaDto);
                        WeixinHandler.sendMsg(sysUser1,
                                String.format("订单[%s]：审核结果[作废], 审核时间[%s], 审核人[%s]",
                                        item.getString("gwcsdocno"),
                                        DateUtils.getDate(DateUtils.PATTERN_yyyy_MM_dd_HH_mm_ss),
                                        currentUser.getNAME())
                        );*/
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return ERROR;
            }
        }
        return new ResponseData(errcode,errmsg);
    }
}
